<template>
    <el-dialog :model-value="props.value" title="设置默认值" width="800px" @closed="props.closed">
        <el-form ref="formRef" :model="form" label-width="120px">
            <el-form-item label="是否必填" required prop="required">
                <el-radio-group v-model="form.required">
                    <el-radio :value="true">是</el-radio>
                    <el-radio :value="false">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <AttributeDefaultValueConfig :form="form" />
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="props.close">取消</el-button>
                <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { type PopupBoxProps } from '@great/utils';
import { modelService } from '@great/services';
import { useRequest } from 'vue-request';
import AttributeDefaultValueConfig from '@/components/AttributeDefaultValueConfig.vue';
import type { FormInstance } from 'element-plus';

interface IProps extends PopupBoxProps {
    detail: Record<string, any>;
    objectName: string;
    callback?: () => void;
}

const props = defineProps<IProps>();

const formRef = useTemplateRef<FormInstance>('formRef');
const form = reactive({
    defaultValueType: '',
    required: false,
    defaultValue: undefined,
    defaultItem: undefined,
    ...props.detail
});

function onSubmit() {
    formRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            run();
        }
    });
}

const { run, loading } = useRequest(
    () => {
        return modelService.attribute.updateExtends({
            defaultValueType: form.defaultValueType || undefined,
            required: form.required,
            defaultItem: form.defaultItem || undefined,
            defaultValue: form.defaultValue || undefined,
            objectName: props.objectName,
            attributeName: props.detail.attributeName
        });
    },
    {
        manual: true,
        onSuccess() {
            props.close();
            props.callback?.();
        }
    }
);
</script>

<style lang="scss" scoped></style>
